package controller

import (
	"admin/model"
	"admin/util"
	"crypto/md5"
	"fmt"

	"github.com/gin-gonic/gin"
)

func Login(ctx *gin.Context) {
	type UserInfo struct {
		UserName string `json:"username"`
		Password string `json:"password"`
	}
	info := UserInfo{}
	ctx.ShouldBind(&info)
	if !(len(info.UserName) > 0 && len(info.Password) > 0) {
		ctx.JSON(200, gin.H{
			"code":    400,
			"message": "用户名或者密码未填写",
		})
		return
	}
	user := model.User{}
	// 进行md5加密
	password := fmt.Sprintf("%x", md5.Sum([]byte(info.Password)))
	count := db.Where("user_name = ? and password = ?", info.UserName, password).Find(&user).RowsAffected
	if count == 0 {
		ctx.JSON(200, gin.H{
			"code":    400,
			"message": "登录失败",
		})
		return
	}
	user.Token = util.RandStr(64)
	db.Save(&user)
	ctx.JSON(200, gin.H{
		"code":    200,
		"message": "登录成功",
		"data": gin.H{
			"token":    user.Token,
			"userName": user.UserName,
		},
	})
}
